<?php
	session_start();
	class User_Model extends MySQL{

		function __construct() {
			MySQL::connect();
		}

		function checkPwd($account, $password) {
			$link = MySQL::connect();
			$account = MySQL::real($account);
			$password = MySQL::real($password);
			$sha1_pass = User_Model::entrypt($password);
			$sql = "SELECT loginid, account, password, flag, shopname FROM LoginUser WHERE account = '$account' AND password = '$sha1_pass'";
			$row = MySQL::query_row($sql);
			if ($account != NULL && $password != NULL && $account == $row[1] && $sha1_pass == $row[2]) {
				if ($row[3] == 0) {
					//not comferm user
					$_SESSION['loginid'] = $row[0];
				}else if ($row[3] == 1) {
					//normal user
					$_SESSION["loginid"] = $row[0];
					if ($row[4] == NULL){
						$_SESSION['shopid'] = 0;
						$shopid = 0;
					}else {	
						$sql = "SELECT shopid FROM Shops WHERE fullname = '$row[4]'";
						$result = MySQL::query_row($sql);
						$shopid = $result[0];
						$_SESSION['shopid'] = $shopid;
					}
					header("location:index.php");
				}else if ($row[3] == 2) {
					//admin user
				}else
					User_Model::errorMsg('You have no permission!!');
			}else {
				User_Model::errorMsg('You have no permission!!');
			}
		}

		function add_user($account, $password, $shopName, $secName, $email) {
			$account = MySQL::real($account);
			$sql = "SELECT * FROM LoginUser WHERE account = '$account'";
			$row = MySQL::query_row($sql);
			if ($row == NULL)
				User_Model::errorMsg('帳號重複');
			else {
				$password = MySQL::real($password);
				$shopName = MySQL::real($shopName);
				$email = MySQL::real($email);
				$password = User_Model::entrypt($password);
				$sql = "INSERT INTO LoginUser VALUES (NULL, '$account', '$password', '$email', NULL, 0)";
				MySQL::query($sql);
				header("location:login.php");
			}
		}

		function getClient($shopid, $flag) {
			$link = MySQL::connect();
			$shopid = MySQL::real($shopid);
			$flag = MySQL::real($flag);
			$sql = "SELECT clientid, clientname, orderofnum, ordertime, arrivetime FROM client WHERE shopid = '$shopid' AND flag = '$flag'";
			$result = mysqli_query($link, $sql);
			while ($row = mysqli_fetch_assoc($result))
				$temp[] = $row;
			echo json_encode($temp);
		}

		function delClient($shopid, $clientid) {
			$link = MySQL::connect();
			$shopid = MySQL::real($shopid);
			$clientid = MySQL::real($clientid);
			$sql = "DELETE FROM client WHERE shopid = '$shopid' AND clientid = '$clientid'";
			$result = mysqli_query($link, $sql);
			$temp = array();
			if ($result == false) {
				$temp['result'] = 'failed';
				$temp['message'] = mysqli_error($link);
			}else
				$temp['result'] = 'success';
			echo json_encode($temp);
		}

		function clientCheckIn($shopid, $clientid) {
			date_default_timezone_set("Asia/Taipei");
			$time = date("Y-m-d H:i");
			$time = date("Y-m-d H:i", strtotime('+10 minutes',strtotime($time)));
			$link = MySQL::connect();
			$shopid = MySQL::real($shopid);
			$clientid = MySQL::real($clientid);
			$sql = "UPDATE client SET flag = 0, arrivetime = '$time' WHERE shopid = '$shopid' AND clientid = '$clientid' AND flag = -1";
			$result = mysqli_query($link, $sql);
			$temp = array();
			if ($result == false) {
				$temp['result'] = 'failed';
				$temp['message'] = mysqli_error($link);
			}else
				$temp['result'] = 'success';
			echo json_encode($temp);
		}

		function assignTable($shopid, $clientid, $table) {
			$link = MySQL::connect();
			$shopid = MySQL::real($shopid);
			$clientid = MySQL::real($clientid);
			$table = MySQL::real($table);
			$json_return = array();
			// 檢查可配置的桌子有無超過可配置數量
			$sql = "SELECT currentnumber, totalnumber FROM tables WHERE shopid = '$shopid' AND type = '$table'";
			$result = mysqli_query($link, $sql);
			if($result != false) {
					$row = mysqli_fetch_row($result);
					if($row != NULL) { // check query tables info value not NULL
						if($row[0] < $row[1]) { // currentnumber < totalnumber

							$sql = "SELECT orderofnum FROM client WHERE shopid = '$shopid' AND clientid = '$clientid'";
							$result = mysqli_query($link, $sql);
							if($result != FALSE) {	
								// check assign 
								$row = mysqli_fetch_row($result);
								if($row[0] <= $table) {	// orderofnum <= table type
									$sql = "UPDATE tables SET currentnumber = currentnumber + 1 WHERE shopid = '$shopid' AND type = '$table'";						
									$result = mysqli_query($link, $sql);
									if($result === TRUE) {
										// assign table to client
										$sql = "UPDATE client SET flag = '$table' WHERE shopid = '$shopid' AND clientid = '$clientid'";
										$result = mysqli_query($link, $sql);
										if($result === TRUE) {
											$json_return['result'] = 'success';
										}else {
											// assign table failed
											$json_return['result'] = 'failed';
											$json_return['message'] = "assign table failed"." ".$sql;
										}
									}else {
										// update table number error
										$json_return['result'] = 'failed';
										$json_return['message'] = "update table number error";
									}
								}else { 
									// orderofnum >= table type
									$json_return['result'] = 'failed';
									$json_return['message'] = "orderOfNumber exceeded assign Table";
								}
							}else {
								// query client orderofnum error
									$json_return['result'] = 'failed';
									$json_return['message'] = "query client ordernum error";							
							}
						}else {
							// currentnumber >= totalnumber
							$json_return['result'] = 'failed';
							$json_return['message'] = 'assignable tables has been exceeded';
						}
					}else {
						// check query tables info is null
						$json_return['result'] = 'failed';
						$json_return['message'] = 'table type does not provided';
					}
			}else {
				// query Table number error
				$json_return['result'] = 'failed';
				$json_return['message'] = 'query table amount error';
			}
			echo json_encode($json_return);
		}

		function finishedEating($shopid, $clientid) {
			date_default_timezone_set("Asia/Taipei");
			$time = date("Y-m-d H:i");
			$link = MySQL::connect();
			$shopid = MySQL::real($shopid);
			$clientid = MySQL::real($clientid);
			$sql = "SELECT * FROM client WHERE shopid = '$shopid' AND clientid = '$clientid'";
			$info = MySQL::query_array($sql);
			$clientname = $info['clientname'];
			$orderofnum = $info['orderofnum'];
			$cellphone = $info['cellphone'];
			$ordertime = $info['ordertime'];
			$arrivetime = $info['arrivetime'];
			$tabletype = $info['flag'];
			$imsi = $info['imsi'];
			$json_return = array();

			//  insert client info into diningrecord
			$sql = "INSERT INTO diningrecord VALUES(NULL, '$clientid', '$shopid', '$clientname', '$orderofnum', '$cellphone', '$ordertime', '$arrivetime', '$time', '$tabletype', '$imsi')";
			$result = mysqli_query($link, $sql);
			if ($result === TRUE) {

				// update table currentnumber
				$sql = "UPDATE tables SET currentnumber = currentnumber - 1 WHERE shopid = '$shopid' AND type = '$tabletype'";
				$result = mysqli_query($link, $sql);
				if($result === TRUE) {
					// delete client info from Client Table
					$sql = "DELETE FROM `androidapp`.`Client` WHERE `Client`.`clientid` = '$clientid'";
					$result = mysqli_query($link, $sql);
					if($result === TRUE) {
						$json_return['result'] = 'success';

					}else {
						// delete client info error
						$json_return['result'] = 'failed';
						$json_return['message'] = "delete client info error";
					}
				}else {
					// update table currentnumber error
					$json_return['result'] = 'failed';
					$json_return['message'] = "update table currentnumber error";
				}
			}else {
				// insert diningrecord error
				$json_return['result'] = 'failed';
				$json_return['message'] = mysqli_error($link);

			}				
			echo json_encode($json_return);
		}

		function clientNotify($shopid, $clientid) {
			date_default_timezone_set("Asia/Taipei");
			$shopid = MySQL::real($shopid);
			$clientid = MySQL::real($clientid);
			$sql = "SELECT fullname FROM shops WHERE shopid = '$shopid'";
			$row = MySQL::query_array($sql);
			$fullname = $row['fullname'];
			$sql = "SELECT arrivetime, gcm_regid FROM client WHERE shopid = '$shopid' AND clientid = '$clientid'";
			$row = MySQL::query_array($sql);
			$arrivetime = $row['arrivetime'];
			$gcm_regid = $row['gcm_regid'];

			$now_time = date("Y-m-d H:i");
			//$end_time = date("Y-m-d H:i", strtotime('+10 minutes',strtotime($start_time)));
			$time = strtotime($arrivetime) - strtotime($now_time);
			$day = floor($time / 3600 / 24);
			$hour = floor(($time - $day * 3600 * 24 ) / 3600);
			$min = floor(($time - $hour * 3600 - $day * 3600 * 24) / 60);

			if ($min <0) {
				//更新arrivetime
				$new_time = date("Y-m-d H:i", strtotime('+10 minutes',strtotime($now_time)));
				$sql = "UPDATE client SET arrivetime = '$new_time' WHERE shopid = '$shopid' AND clientid = '$clientid'";
				MySQL::query($sql);
				$new_min = 10;
			}else{
				//十分鐘以內到店，回傳arrivetime - new_time的分鐘
				$new_min = $min;
			}

			$content = "您所排的店家'".$fullanme."'已有位子，請在".$new_min."分鐘內到店";
			$result = forPhoneModel::GCM_send($gcm_regid, $content);
			if ($result != null) {
				$temp['result'] = 'failed';
				$temp['message'] = 'Curl failed: '.$result;
			}else
				$temp['result'] = 'success';
			echo json_encode($temp);
		}

		function getShopState($shopid) {
			$shopid = MySQL::real($shopid);
			$sql = "SELECT maxofnumber, currentnumber FROM shops WHERE shopid = '$shopid'";
			$result = MySQL::query_array($sql);
			$temp = array();
			$temp['maxNum'] = $result['maxofnumber'];
			$temp['cuttentNum'] = $result['currentnumber'];
			echo json_encode($temp);
		}

		function shopSwitch($shopid, $switch) {
			$error = false;
			$link = MySQL::connect();
			$shopid = MySQL::real($shopid);
			if ($switch == 'on')
				$sql = "UPDATE shops SET open = 1 WHERE shopid = '$shopid'";
			else if ($switch == 'off')
				$sql = "UPDATE shops SET open = 0 WHERE shopid = '$shopid'";
			else
				$error = true;
			$result = mysqli_query($link, $sql);
			if ($result === FALSE) {
				$temp['result'] = 'failed';
				$temp['message'] = mysqli_error($link);
			}else if ($error == true){
				$temp['result'] = 'failed';
				$temp['message'] = 'sql error';
			}else
				$temp['result'] = 'success';
			echo json_encode($temp);
		}

		function entrypt($str) {
			$temp = "\x0a";
			$temp = $str.$temp;
			return sha1($temp);
		}

		function errorMsg($str) {
			echo '<noscript>'.$str.'</noscript>';
			echo "<script language='javascript'>";
			echo "alert('".$str."');";
			echo "history.back();";
			echo "</script>";
		}
	}
?>